<template>
  <div class="base f_col f_r_cnt f_jc_cnt">
    <div v-if="loadingVisible" style="width: 100%;padding: 0 60px;box-sizing: border-box;">
      <p class="loading_text">数据加载中</p>
      <mt-progress :value="percent" :bar-height="10">
        <div slot="end">{{percent}}%</div>
      </mt-progress>
    </div>
  </div>
</template>

<script>
import {MessageBox} from 'mint-ui'
import {
  getCordovaFile,
  remove,
  checkIfFileExists,
  moveTo,
  readFile,
  createFile
} from '../../static/corodvajs/c_fileplugin.js'

import {unzip} from '../../static/corodvajs/c_zipdata.js'
import {requestPermission} from '../../static/corodvajs/c_permission'

export default {
  name: 'base',
  data () {
    return {
      cordovaFile: {},
      applicationStoragePath: '',
      newDataZipPath: '',
      percent: 0,
      loadingVisible: true,
      debugModule: false
    }
  },
  mounted () {
    this.cordovaFile = getCordovaFile()
    this.applicationStoragePath = this.cordovaFile.externalApplicationStorageDirectory
    document.addEventListener('pause', this.onResume)
    // this.checkPermission()
    let isInited = localStorage.getItem('inited')
    if (isInited) {
      this.goToHome()
    } else {
      this.checkDataZip()
    }
  },
  destroyed () {
    // document.removeEventListener('pause', this.onResume)
  },
  methods: {
    checkPermission () {
      requestPermission(function (status) {
        if (!status.hasPermission) {
          this.errMsg('请开启存储权限')
        }
      }, function () {
        this.errMsg('请开启存储权限')
      })
    },
    checkDataZip () {
      console.log('加载数据文件')
      let otherDir = this.cordovaFile.externalRootDirectory + 'Others/'
      let dataZipFilePath = otherDir + '/landscape-data.zip'
      console.log('数据文件目录:', dataZipFilePath)
      checkIfFileExists(dataZipFilePath, (fileEntry) => {
        this.moveZipData(fileEntry)
      }, () => {
        console.log('checkIfFileExists File not exists!')
        this.loadData()
      })
    },
    goToHome () {
      this.loadExtraHomeCss()
    },
    moveZipData (fileEntity) {
      let appDataDir = this.applicationStoragePath
      // 移动数据文件
      moveTo(fileEntity, appDataDir, null, (file) => {
        this.removeOldData()
        this.newDataZipPath = file.toURL()
      }, (err) => {
        console.error('move filed', err)
      })
    },
    removeOldData () {
      let appDataDir = this.applicationStoragePath + 'export/'
      checkIfFileExists(appDataDir, (fileEntry) => {
        // 旧的文件存在，需要删除
        remove(appDataDir, () => {
          console.log(appDataDir, 'had been remove,then unzip new data')
          this.unZipData(this.newDataZipPath)
        }, (err) => {
          console.log('remove fail', err)
        })
      }, () => {
        console.log('export not exists! unzip new data')
        this.unZipData(this.newDataZipPath)
      })
    },
    unZipData (fileURL) {
      let appDataDir = this.applicationStoragePath
      let _this = this
      unzip(fileURL, appDataDir, (result) => {
        console.log('unzip result', result)
        this.loadData()
      }, function (progressEvent) {
        console.log('progressEvent', progressEvent)
        let tp = Math.round((progressEvent.loaded / progressEvent.total) * 100)
        console.log('unzip process=', tp)
        _this.percent = tp
      })
    },
    loadData () {
      let dataPath = this.applicationStoragePath + '/export/data.json'
      checkIfFileExists(dataPath, (fileEntity) => {
        console.log('data json ready to read')
        this.readDataJson(fileEntity)
      }, (err) => {
        console.error('data.json does not exists', err)
        // 数据文件不存在，需报错
        this.errMsg('无数据文件，请检查后重新打开再试')
      })
    },
    readDataJson (fileEntity) {
      let attachmentPath = this.applicationStoragePath + 'export/'
      readFile(fileEntity, (data) => {
        console.log('data json load successful')
        this.dataObj = JSON.parse(data)
        // 遍历处理moduleList
        let tempModuleList = this.dataObj.moduleList.map(mitem => {
          console.log('module item', mitem)
          if (mitem.avatarPath) {
            mitem.avatarPath = attachmentPath + mitem.avatarPath
          }
          return mitem
        })
        // 遍历处理spotList
        tempModuleList.forEach(module => {
          let moduleId = module.id
          let spotList = this.dataObj[`M-${moduleId}`]
          let tempSpotList = spotList.map(sitem => {
            if (sitem.avatarPath) {
              sitem.avatarPath = attachmentPath + sitem.avatarPath
            }
            if (sitem.videoPath) {
              sitem.videoPath = attachmentPath + sitem.videoPath
            }
            if (sitem.content) {
              sitem.content = this.processContent(sitem.content, attachmentPath)
            }
            return sitem
          })
          this.dataObj[`M-${moduleId}`] = tempSpotList
        })
        this.dataObj.moduleList = tempModuleList
        console.log('data obj', this.dataObj)
        localStorage.setItem('data', JSON.stringify(this.dataObj))
        localStorage.setItem('inited', true)
        // 初始化完成，跳转主页
        this.goToHome()
      })
    },
    processContent (content, attachmentPath) {
      let specialTag = /src="\/api\/attachment\//g
      let targetTag = 'src="' + attachmentPath
      content = content.replace(specialTag, targetTag)
      console.log(content)
      return content
    },
    loadExtraHomeCss () {
      let dataPath = this.applicationStoragePath + '/css.json'
      // let dataPath = this.applicationStoragePath + '/export/data.json'
      if (!this.debugModule) {
        // 非debug模式，将路径修改
        dataPath = this.applicationStoragePath + '/export/data.json'
      }
      checkIfFileExists(dataPath, (fileEntity) => {
        console.log('css json ready to read')
        this.readCssJson(fileEntity)
      }, (err) => {
        console.error('css.json does not exists', err)
        // 数据文件不存在，需报错
        this.errMsg('css数据文件不存在，请检查后重新打开再试')
      })
    },
    readCssJson (fileEntity) {
      if (!this.debugModule) {
        // 非debug模式，将路径修改
        let data = this.getMemoryCssContent()
        console.log('css json load successful')
        localStorage.setItem('dataStyles', data)
        this.loadingVisible = false
        this.$router.push('/home')
      } else {
        // 从本地文件获取
        readFile(fileEntity, (data) => {
          console.log('css json load successful')
          localStorage.setItem('dataStyles', data)
          this.loadingVisible = false
          this.$router.push('/home')
        })
      }
    },
    errMsg (msg) {
      MessageBox.alert(msg).then(action => {
        console.log('退出程序')
      })
    },
    onResume () {
      console.log('on resume')
      localStorage.removeItem('inited')
    },
    getMemoryCssContent () {
      let str = '{"dataList":[{"id":1,"name":"额伊特湖 (大天鹅湖)"},{"id":2,"name":"阿布什格湖"},{"id":3,"name":"布日呼图湖"},{"id":4,"name":"巴格达布苏湖"},{"id":5,"name":"吉格尔其库湖"},{"id":6,"name":"阿德格伊克尔湖"},{"id":7,"name":"额肯伊克尔湖"},{"id":8,"name":"天鹅湖景区沙金园度假村"},{"id":9,"name":"查干布湖"},{"id":10,"name":"乌库太湖"},{"id":11,"name":"霍林高勒湖"},{"id":12,"name":"通格图湖"},{"id":13,"name":"温布中转站"},{"id":14,"name":"天鹅湖游客接待中心"},{"id":15,"name":"天鹅湖蒙古大营"},{"id":16,"name":"与沙共舞"},{"id":17,"name":"巴彦浩特镇"}],"pointStyles":[{"uid":"1","top":"13px","left":"175px"},{"uid":"2","top":"80px","left":"98px"},{"uid":"3","top":"105px","left":"229px"},{"uid":"4","top":"156px","left":"205px"},{"uid":"5","top":"169px","left":"298px"},{"uid":"6","top":"195px","left":"495px"},{"uid":"7","top":"219px","left":"428px"},{"uid":"8","top":"231px","left":"510px"},{"uid":"9","top":"268px","left":"219px"},{"uid":"10","top":"265px","left":"276px"},{"uid":"11","top":"255px","left":"368px"},{"uid":"12","bottom":"202px","left":"405px"},{"uid":"13","bottom":"227px","right":"279px"},{"uid":"14","bottom":"176px","right":"116px"},{"uid":"15","bottom":"128px","right":"123px"},{"uid":"16","bottom":"120px","right":"185px"}],"imgStyles":[{"uid":"1","top":"10px","left":"210px"},{"uid":"2","top":"46px","left":"70px"},{"uid":"3","top":"70px","left":"196px"},{"uid":"4","top":"198px","left":"160px"},{"uid":"5","top":"135px","left":"260px"},{"uid":"6","top":"155px","left":"438px"},{"uid":"7","top":"186px","left":"380px"},{"uid":"8","top":"226px","left":"540px"},{"uid":"9","top":"310px","left":"170px"},{"uid":"10","top":"308px","left":"261px"},{"uid":"11","top":"300px","left":"354px"},{"uid":"12","bottom":"166px","left":"384px"},{"uid":"13","bottom":"270px","right":"245px"},{"uid":"14","bottom":"220px","right":"50px"},{"uid":"15","bottom":"91px","right":"58px"},{"uid":"16","bottom":"164px","right":"160px"}]}'
      return str
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
  .base
    height: 100%
    width: 100%
    color #333

    .loading_text
      width 100%
      font-size 16px
      margin-bottom 10px
      text-align center
</style>
